package com.spring.demo.spring_boot.service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spring.demo.spring_boot.domain.Resource;
import com.spring.demo.spring_boot.domain.Role;
import com.spring.demo.spring_boot.domain.RoleResource;
import com.spring.demo.spring_boot.domain.UserInfo;
import com.spring.demo.spring_boot.domain.UserRole;
import com.spring.demo.spring_boot.mapper.ResourceMapper;
import com.spring.demo.spring_boot.mapper.RoleMapper;
import com.spring.demo.spring_boot.mapper.RoleResourceMapper;
import com.spring.demo.spring_boot.mapper.UserInfoMapper;
import com.spring.demo.spring_boot.mapper.UserRoleMapper;

/**
 * 
 * @author 王辉阳
 * @date 2017年8月15日 上午9:40:26
 * @description 权限service
 */
@Service
public class SecurityService {
	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private ResourceMapper resourceMapper;
	@Autowired
	private RoleResourceMapper roleResourceMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;

	/**
	 * 获取用户所有角色
	 * 
	 * @param userId
	 * @return
	 */
	public Set<Role> rolesOfUser(String userId) {
		List<UserRole> userRoles = userRoleMapper.findByUserId(userId);
		String roleIds = userRoles.stream().map(x -> "'" + x.getRoleId() + "'").collect(Collectors.joining(", "));
		List<Role> roleList = roleMapper.findByRoleIds(roleIds);
		return roleList.stream().collect(Collectors.toSet());
	}

	/**
	 * 获取角色所有资源
	 * 
	 * @return
	 */
	public Set<Resource> resourcesOfRoles(Set<Role> roles) {
		// 获取到所有role Ids
		String roleIds = roles.stream().map(x -> "'" + x.getRoleId() + "'").collect(Collectors.joining(", "));
		// 中间表关联查询到所有的资源 ids
		List<RoleResource> roleResources = roleResourceMapper.findByRoleIds(roleIds);

		// 从而获取所有资源
		String resourceIds = roleResources.stream().map(x -> "'" + x.getResId() + "'").collect(Collectors.joining(","));
		List<Resource> resources = resourceMapper.findByIds(resourceIds);
		return resources.stream().collect(Collectors.toSet());
	}

	public UserInfo findByName(String username) {
		return userInfoMapper.findByName(username);
	}

}
